package com.easyfun.healthmagicbox;

import com.easyfun.healthmagicbox.R;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;
import com.easyfun.healthmagicbox.alarmclock.AlarmSettingActivity;
import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.comm.PersonQuestionsDownloadTask;
import com.easyfun.healthmagicbox.comm.ReferenceDataDescriptionDownloadTask;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.HealthInputTypeEnum;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.DataReferenceDescription;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.pojo.PersonProfile;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.widget.CustomDialogTemplate;
import com.easyfun.healthmagicbox.widget.CustomDialogUtil;
import com.j256.ormlite.dao.Dao;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.FloatMath;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

public class SubGraphicReportActivity extends BaseActivity implements
		DatabaseAccess
// ,OnTouchListener

{
	final static String LOG_TAG = SubGraphicReportActivity.class.toString();
	private XYPlot plot;

	Vector<Integer> items = new Vector<Integer>();
	Vector<Boolean> selected = new Vector<Boolean>();

	private int selectedValueType = -1;
	private float averageHealthData = -1;
	private float latestHealthData = -1;
	private PointF minXY = null;
	private PointF maxXY = null;
	private Long minFixedX = Long.valueOf(0);
	private Long maxFixedX = Long.valueOf(0);
	
	private float maxFixedY = (float) 0.0;
	private float minFixedY = (float) 0.0;
	
	CustomDialogUtil dataPickerDialog;
	
	
	private Button butAlarmClock;
	private ArrayList<String> typeNames;
	private WebView webView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.two);

		webView = (WebView)findViewById(R.id.graph_Standard);
		webView.setBackgroundColor(0);
		if (!checkPersonId())
			return;

		// fun little snippet that prevents users from taking screenshots
		// on ICS+ devices :-)
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
				WindowManager.LayoutParams.FLAG_SECURE);
		
		 /*
         * Setup the Plots
         */
		
		// initialize our XYPlot reference:
		plot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
		initialXYPlot();

//		initialReferenceDataDescription();
		
		Button butselect = (Button) findViewById(R.id.but_selectreport);
		getItems();
		typeNames = new ArrayList<String>();//change CharSequence[] to ArrayList<String>
		for (int i = 0; i < items.size(); i++) {
			typeNames.add( ConstantData.HealthData.get(items.get(i)));
		}
		
		dataPickerDialog = new CustomDialogUtil((Context)this, 
				typeNames, getString(R.string.custom_dialog_default_title));
		butselect.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dataPickerDialog.createDialog(false);  //this dialog is single choice mode.

			}
		});
		
		
		Button butreset = (Button) findViewById(R.id.but_resetreport);
		butreset.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if ((minXY == null)||(maxXY == null))
					return;
				minXY.x = minFixedX.floatValue();
				maxXY.x = maxFixedX.floatValue();
					
				if(minXY.x == maxXY.x) {
					//this means we have only one record. how to handle it? So far, I am thinking of a workaround
					//here to add two extra slots in domain space at beginning and end respectively. as domain is 
					//calculated as time, so I minus 1 mins in front of the space and add 1 mins at the edn.
					minXY.x = (float)(minFixedX - 60.0 * 1000);//ms, 1 min = 60s;
					maxXY.x = (float)(maxFixedX + 60.0 * 1000);
				} 
				
				plot.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.FIXED);
				plot.redraw();		
			}
		});
	
		butAlarmClock = (Button) findViewById(R.id.butAlarmClock);
		butAlarmClock.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Intent intent_pp = new Intent(
						SubGraphicReportActivity.this, AlarmSettingActivity.class);
				intent_pp.putExtra(ConstantData.HMBPERSONID, m_personid);
					SubGraphicReportActivity.this.startActivity(intent_pp);
			}
		});
	}

	void queryAndDrawData(ArrayList<Boolean> selected) {
		try {
			Dao<HealthInputData, Integer> inputDataDao = getHelper(this)
					.getInputDataDao();

			Set<XYSeries> oldSeriesSet = plot.getSeriesSet();
			for(XYSeries series : oldSeriesSet) {
				plot.removeSeries(series);
			}
					
			for (Integer item : items) {
				if (selected.get(items.indexOf(item)) == true) {
					selectedValueType = item;
					List<HealthInputData> hids = inputDataDao.queryBuilder()
							.orderBy("valueTime", true).where()
							.eq("personID", m_personid).and()
							.eq("valueType", item).query();
					List<Number> seriesXNum = new ArrayList<Number>();
					List<Number> seriesYNum = new ArrayList<Number>();
					if (hids.size() > 0) {
						minFixedX = hids.get(0).getValueTime();
						maxFixedX = hids.get(0).getValueTime();
						
						minFixedY = Float.valueOf(hids.get(0).getValueData());
						maxFixedY = Float.valueOf(hids.get(0).getValueData());
					
					}
					
					float valueData = 0;
					for (HealthInputData hid : hids) {
						valueData += Float.valueOf(hid.getValueData());
						seriesXNum.add(hid.getValueTime());
						seriesYNum.add(Float.valueOf(hid.getValueData()));
						if (hid.getValueTime() < minFixedX) {
							minFixedX = hid.getValueTime();
						}
						if (hid.getValueTime() > maxFixedX) {
							maxFixedX = hid.getValueTime();
						}
						
						if(Float.valueOf(hid.getValueData()) < minFixedY) {
							minFixedY = Float.valueOf(hid.getValueData());
						}else if(Float.valueOf(hid.getValueData()) > maxFixedY) {
							maxFixedY = Float.valueOf(hid.getValueData());
						}
						latestHealthData = Float.valueOf(hid.getValueData());
					}
					averageHealthData = valueData / hids.size();
					
					// scaleToOne();

					// Create a couple arrays of y-values to plot:
					// Number[] series1Numbers = {1, 8, 5, 2, 7, 4};
					// Number[] series2Numbers = {4, 6, 3, 8, 2, 10};
					// drawYLine(Arrays.asList(series2Numbers),"Line 2","",R.xml.line_point_formatter_with_plf2);
					
					if (items.indexOf(item)<typeNames.size())
					{
						drawXYLine(seriesXNum, seriesYNum, typeNames.get(items.indexOf(item)), "",
								R.xml.line_point_formatter_with_plf1);
					}
					
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}

		// set X (domain) format
		
		plot.setDomainValueFormat(new Format() {

			private SimpleDateFormat dateFormat = new SimpleDateFormat(
					"MM-dd HH:mm");

			@Override
			public StringBuffer format(Object obj, StringBuffer toAppendTo,
					FieldPosition pos) {

				// because our timestamps are in seconds and SimpleDateFormat
				// expects milliseconds
				// we multiply our timestamp by 1000:
				long timestamp = ((Number) obj).longValue();
				Date date = new Date(timestamp);
				return dateFormat.format(date, toAppendTo, pos);
			}

			@Override
			public Object parseObject(String source, ParsePosition pos) {
				return null;

			}
		});

		// reduce the number of range labels
		plot.setTicksPerRangeLabel(3);
		
		//we need to set range boundaries before rendering
	
		plot.getGraphWidget().setDomainLabelOrientation(0);
		plot.calculateMinMaxVals();
		/*
		minXY = new PointF(plot.getCalculatedMinX().floatValue(), plot
				.getCalculatedMinY().floatValue());
		maxXY = new PointF(plot.getCalculatedMaxX().floatValue(), plot
				.getCalculatedMaxY().floatValue());
				*/
		minXY = new PointF(minFixedX.floatValue(), minFixedY);
		maxXY = new PointF(maxFixedX.floatValue(), maxFixedY);
		if(minXY.x == maxXY.x) {
			//this means we have only one record. how to handle it? So far, I am thinking of a workaround
			//here to add two extra slots in domain space at beginning and end respectively. as domain is 
			//calculated as time, so I minus 1 mins in front of the space and add 1 mins at the edn.
			minXY.x = (float) (minFixedX - 60.0 * 1000);//ms, 1 min = 60s;
			maxXY.x = (float) (maxFixedX + 60.0 * 1000);
		} else {
			minXY.x = (float) (minFixedX - 0.1 * (maxFixedX - minFixedX));
			maxXY.x = (float) (maxFixedX + 0.1 * (maxFixedX - minFixedX));
		}
		
		//same to range 
	/*	if(minXY.y == maxXY.y)
		{*/
			//we add 10% at beginning and end respectively
			minXY.y = (float) (maxXY.y * (1 - 0.1));
			maxXY.y = (float) (maxXY.y * (1 + 0.1));
	/*	}
*/
		plot.setRangeBoundaries(0, maxXY.y, BoundaryMode.FIXED);
		plot.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.FIXED);
		
		Paint bgPaint = new Paint();
		bgPaint.setColor(Color.BLACK);
		bgPaint.setStyle(Paint.Style.FILL);
		bgPaint.setAlpha(40);
		
		plot.getLegendWidget().setBackgroundPaint(bgPaint);
		plot.redraw();
	}
	

	void drawYLine(List<Number> yvalues, String xname, String yname,
			int xmlCfgId) {
		// Turn the above arrays into XYSeries':
		XYSeries series1 = new SimpleXYSeries(yvalues, // SimpleXYSeries takes a
														// List so turn our
														// array into a List
				SimpleXYSeries.ArrayFormat.Y_VALS_ONLY, // means use the element
														// index as the x value
				xname); // Set the display title of the series

		// Create a formatter to use for drawing a series using
		// LineAndPointRenderer
		// and configure it from xml:
		LineAndPointFormatter series1Format = new LineAndPointFormatter();
		series1Format.setPointLabelFormatter(new PointLabelFormatter());
		series1Format.configure(getApplicationContext(), xmlCfgId);

		// add a new series' to the xyplot:
		plot.addSeries(series1, series1Format);
	}

	void drawXYLine(List<Number> xvalues, List<Number> yvalues, String xname,
			String yname, int xmlCfgId) {

		// Turn the above arrays into XYSeries':
		XYSeries series1 = new SimpleXYSeries(xvalues, yvalues, // SimpleXYSeries
																// takes a List
																// so turn our
																// array into a
																// List
				// Y_VALS_ONLY means use the element index as the x value
				xname); // Set the display title of the series

		// setup our line fill paint to be a slightly transparent gradient:
		Paint lineFill = new Paint();

		// lineFill.setAlpha(200);

		// lineFill.setShader(new LinearGradient(0, 0, 200, 200, Color.WHITE,
		// Color.GREEN, Shader.TileMode.CLAMP));
		// lineFill.setColor(Color.BLUE);

		// LineAndPointFormatter formatter = new
		// LineAndPointFormatter(Color.rgb(
		// 0, 0, 0), Color.BLUE, Color.RED, null);
		// formatter.setFillPaint(lineFill);
		// Create a formatter to use for drawing a series using
		// LineAndPointRenderer:

		LineAndPointFormatter formatter = new LineAndPointFormatter();
		formatter.setPointLabelFormatter(new PointLabelFormatter());
		formatter.configure(getApplicationContext(), xmlCfgId);

		/*
		 * // Create a formatter to use for drawing a series using
		 * LineAndPointRenderer // and configure it from xml:
		 * LineAndPointFormatter series1Format = new LineAndPointFormatter();
		 * series1Format.setPointLabelFormatter(new PointLabelFormatter());
		 * series1Format.configure(getApplicationContext(),xmlCfgId);
		 */
		// add a new series' to the xyplot:
		plot.addSeries(series1, formatter); // series1Format

	}

	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(context);
	}

	void getItems() {
		Dao<HealthInputData, Integer> inputDataDao;
		// get our dao
		try {
			inputDataDao = getHelper(this).getInputDataDao();

			List<HealthInputData> types = inputDataDao.queryBuilder()
					.distinct().selectColumns("valueType").where()
					.eq("personID", m_personid).query();
			items.clear();
			selected.clear();
			for (HealthInputData type : types) {
				items.add(type.getValueType());
				selected.add(new Boolean(false));
			}
			Log.i(LOG_TAG, "get last input data.");
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		}
	}

	private boolean[] toPrimitiveArray(final List<Boolean> booleanList) {
		final boolean[] primitives = new boolean[booleanList.size()];
		int index = 0;
		for (Boolean object : booleanList) {
			primitives[index++] = object;
		}
		return primitives;
	}

	

	protected void createDialog(int id) {
		if (items.size() == 0) {
			Toast.makeText(getApplicationContext(), "您还没有录入健康数据呀！",
					Toast.LENGTH_SHORT).show();
			return;
		}
/*		Dialog dialog = null;
*/		switch (id) {
		case 1:
			String[] typenames = new String[items.size()];//change CharSequence[] to String[]
			for (int i = 0; i < items.size(); i++) {
				typenames[i] = ConstantData.HealthData.get(items.get(i));
			}
			
			//try to launch personDataDialog, and waiting for the results.
			 Intent personDataIntent = new Intent(this, CustomDialogTemplate.class);
			 personDataIntent.putExtra(ConstantData.CUSTOM_DIALOG_INPUT_DATA, typenames);
			 
			 String dialogPersonDataTitle = getString(R.string.dialog_person_data_title);
			 personDataIntent.putExtra(ConstantData.CUSTOM_DIALOG_TITLE, dialogPersonDataTitle);
/*			 personDataIntent.putExtra(ConstantData.CUSTOM_DIALOG_ACTION, new )
*/	         startActivityForResult(personDataIntent, ConstantData.CUSTOM_DIALOG_REQUST_ID);

			break;
		}
		return;
	}

	  public void onActivityResult(int requestCode, int resultCode, Intent data) {     
	        switch (requestCode) {
	        case ConstantData.CUSTOM_DIALOG_REQUST_ID:
	            // When user selects one with success
	            if (resultCode == Activity.RESULT_OK) {
	                // draw Grid View
	            	ArrayList<Boolean>selected = (ArrayList<Boolean>)data.getExtras().getSerializable(ConstantData.CUSTOM_DIALOG_RETURN_DATA);
	            	if(selected != null){
		            	queryAndDrawData(selected);
		                showTop(selectedValueType);
	            	}
	                
	            }
	            break;
	        }
	    }
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {

		super.onWindowFocusChanged(hasFocus);
		if (hasFocus) {
			//update 
			getItems();
			ArrayList<String> typeNames = new ArrayList<String>();
			for (int i = 0; i < items.size(); i++) {
				typeNames.add( ConstantData.HealthData.get(items.get(i)));
			}
			dataPickerDialog.setItems(typeNames);
		}
	}

	// Definition of the touch states
	static final int NONE = 0;
	static final int ONE_FINGER_DRAG = 1;
	static final int TWO_FINGERS_DRAG = 2;
	int mode = NONE;

	PointF firstFinger;
	float distBetweenFingers;
	boolean stopThread = false;

	public boolean inRangeOfView(View view, MotionEvent ev) {
		boolean result = false;
		int[] location = new int[2];
		view.getLocationOnScreen(location);
		int x = location[0];
		int y = location[1];
		int rx = x + view.getWidth();
		int ly = y + view.getHeight();
		if ((ev.getRawX() > x) && (ev.getRawX() < rx) && (ev.getRawY() > y)
				&& (ev.getRawY() < ly)) {
			result = true;
		} else {
			result = false;
		}
		return result;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

		boolean result = false;
		if (inRangeOfView(plot, ev)) {
			Log.i("dispatchTouchEvent", "MainActivity");
			onTouched(ev);
			if (ViewPagerActivity.getPager() != null)
				ViewPagerActivity.getPager().setPagingEnabled(false);
			result = true;
		} else {
			Log.i("dispatchTouchEvent", "MainActivity2222");
			if (ViewPagerActivity.getPager() != null)
				ViewPagerActivity.getPager().setPagingEnabled(true);
			result = super.dispatchTouchEvent(ev);
		}
		return result;
	}

	public boolean onTouched(MotionEvent event) {
		if (minXY == null)
			return false;
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN: // Start gesture
			firstFinger = new PointF(event.getX(), event.getY());
			mode = ONE_FINGER_DRAG;
			stopThread = true;
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_POINTER_UP:
			mode = NONE;
			break;
		case MotionEvent.ACTION_POINTER_DOWN: // second finger
			distBetweenFingers = spacing(event);
			// the distance check is done to avoid false alarms
			if (distBetweenFingers > 5f) {
				mode = TWO_FINGERS_DRAG;
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if (mode == ONE_FINGER_DRAG) {
				PointF oldFirstFinger = firstFinger;
				firstFinger = new PointF(event.getX(), event.getY());
				scroll(oldFirstFinger.x - firstFinger.x);
				plot.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.FIXED);
				plot.redraw();

			} else if (mode == TWO_FINGERS_DRAG) {
				float oldDist = distBetweenFingers;
				distBetweenFingers = spacing(event);
				zoom(oldDist / distBetweenFingers);
				plot.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.FIXED);
				plot.redraw();
			}
			break;
		}
		return true;
	}

	private void zoom(float scale) {
		float domainSpan = maxXY.x - minXY.x;
		float domainMidPoint = maxXY.x - domainSpan / 2.0f;
		float offset = domainSpan * scale / 2.0f;

		minXY.x = domainMidPoint - offset;
		maxXY.x = domainMidPoint + offset;

		minXY.x = Math.max(minXY.x, minFixedX);
		maxXY.x = Math.min(maxXY.x, maxFixedX);
		clampToDomainBounds(domainSpan);
	}

	private void scroll(float pan) {
		float domainSpan = maxXY.x - minXY.x;
		float step = domainSpan / plot.getWidth();
		float offset = pan * step;
		minXY.x = minXY.x + offset;
		maxXY.x = maxXY.x + offset;
		clampToDomainBounds(domainSpan);
	}

	private void clampToDomainBounds(float domainSpan) {
		float leftBoundary = minFixedX;
		float rightBoundary = maxFixedX;
		// enforce left scroll boundary:
		if (minXY.x < leftBoundary) {
			minXY.x = leftBoundary;
			maxXY.x = leftBoundary + domainSpan;
		} else if (maxXY.x > maxFixedX) {
			maxXY.x = rightBoundary;
			minXY.x = rightBoundary - domainSpan;
		}
	}

	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return FloatMath.sqrt(x * x + y * y);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		return super.onOptionsItemSelected(item, this);
	}
	
	private void showTop(int valueType)
	{
		float lowerLimitValue = 0;
		float upperLimitValue = 0;
		try 
		{
			Dao<DataReferenceDescription, Integer> referenceDataDao = getHelper(this).getReferenceDataDao();
			Dao<PersonProfile, Integer> personProfileDao = getHelper(this).getPersonProfileDao();
			
			webView.setWebViewClient(new WebViewClient());
		
			String referenceDataDescription = null;
			List<PersonProfile> profiles = personProfileDao.queryForEq("personID", m_personid);
			List<DataReferenceDescription> referenceDataList = null;
			int gender = ConstantData.REFERENCE_DATA_ANY;;
			Double dependencyData = -1.0;
			
		
			if(valueType == HealthInputTypeEnum.TIZHONG.toInteger())
			{	
				dependencyData = profiles.get(0).getHeigth();
				gender = getGender(profiles.get(0));
				referenceDataList = referenceDataDao.queryBuilder().where()
															.eq("referenceDataType", valueType)
															.and().ge("dependencyUpperLimitData", dependencyData)
															.and().le("dependencyLowerLimitData", dependencyData)
															.and().eq("gender", gender)
															.query();
			}
			else if(valueType == HealthInputTypeEnum.SHENGAO.toInteger()
					|| valueType == HealthInputTypeEnum.YAOWEI.toInteger()
					|| valueType == HealthInputTypeEnum.XUEYA_DIYA.toInteger()
					|| valueType == HealthInputTypeEnum.XUEYA_GAOYA.toInteger())
			{
				int age = profiles.get(0).getAge();
				dependencyData = (double) age;
				gender = getGender(profiles.get(0));
			
			} 
			else if(valueType == HealthInputTypeEnum.XUETANG_CANHOU.toInteger()
					|| valueType == HealthInputTypeEnum.XUETANG_CANQIAN.toInteger()
					|| valueType == HealthInputTypeEnum.TIWEN.toInteger())
			{
				dependencyData = (double)ConstantData.REFERENCE_DATA_ANY;
				gender = ConstantData.REFERENCE_DATA_ANY;
				
			}
			
			
			referenceDataList = referenceDataDao.queryBuilder().where()
					.eq("referenceDataType", valueType)
					.and().ge("dependencyUpperLimitData", dependencyData)
					.and().le("dependencyLowerLimitData", dependencyData)
					.and().eq("gender", gender)
					.query();
			/*html layout will be:
			 * 您的指标： XXXX
			 * 参考值范围： XXX -XXX
			 * 结论
			 * */
			DecimalFormat df = new DecimalFormat();
			String style = "0.0";
			df.applyPattern(style);
			String suggestions= "最新测量值："  + df.format(latestHealthData) + "<br/>";
			suggestions += "长期平均值：" + df.format(averageHealthData) + "<br/>";		
			if(referenceDataList == null || referenceDataList.size() == 0) 
			{
				referenceDataDescription = "正常值范围：现在还没有对应的参考数据";
				lowerLimitValue = 0;
				upperLimitValue = 0;
			} else {
				referenceDataDescription = "正常值范围：" + referenceDataList.get(0).getReferenceDataDescription();
				upperLimitValue = referenceDataList.get(0).getUpperLimitData();
				lowerLimitValue = referenceDataList.get(0).getLowerLimitData();
			}
			suggestions += referenceDataDescription;
			
			if(lowerLimitValue != 0 && upperLimitValue != 0)
			{
				if(averageHealthData < upperLimitValue && averageHealthData > lowerLimitValue)
				{
					suggestions += "<br/><br/>" + "<font color='#80fd80'>恭喜, 您的数据在正常值范围内。</font>";
				}else if (averageHealthData > upperLimitValue) {
					suggestions += "<br/><br/>" + "<font color=\"#fd8080\">您的数据超过了正常值上限， 请注意日常生活习惯。 </font>";
				}else if (averageHealthData < lowerLimitValue) {
					suggestions += "<br/><br/>" + "<font color=\"#fd8080\">您的数据低于正常值下限，请注意日常生活习惯。</font>";
				}else
				{
					suggestions += "<br/><br/>" + "对不起，现在暂时还没有对应的参考数据:)";
				}
			}
			
			String description = generateHTMLReferenceDataDescription(suggestions);
			webView.loadDataWithBaseURL(null, description, "text/html", "utf-8", null);
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		}
	}
	
	private int getGender(PersonProfile personProfile) {
		int gender =0;
		if(personProfile.getSex().equalsIgnoreCase("女")){
			gender = 2;
		} else{
			gender = 1;
		}
		return gender;
	}

	private String generateHTMLReferenceDataDescription(String rawReferenceDataDescription)
	{
		String strHTMLOutput = null;
		
		strHTMLOutput = "<html>";
		strHTMLOutput +=   "<body>";
		strHTMLOutput +=       "<div>";
		strHTMLOutput +=    		"<p>";
		strHTMLOutput +=          		"<font size='4' color='#ffffff'>";
		strHTMLOutput +=    				rawReferenceDataDescription;
		strHTMLOutput +=          		"</font>";
		strHTMLOutput +=    		"</p>";
		strHTMLOutput +=        "</div>";
		strHTMLOutput +=   "</body>";
		strHTMLOutput += "</html>";
		
		
		return strHTMLOutput;
	}
	
	
	private void initialXYPlot()
	{
		plot.setPlotMargins(0, 0, 0, 0);

        plot.setPlotPadding(0, 0, 0, 0);
		// This gets rid of the black border (up to the graph) there is no black
		// border around the labels
		plot.getBackgroundPaint().setColor(Color.WHITE);
		plot.setDomainStepValue(5);
		// This gets rid of the black behind the graph
		plot.getGraphWidget().getBackgroundPaint().setColor(Color.TRANSPARENT);
		plot.setBackgroundColor(Color.WHITE);

		plot.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE);
		plot.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);

		plot.getGraphWidget().getDomainLabelPaint().setColor(Color.BLACK);
		plot.getGraphWidget().getRangeLabelPaint().setColor(Color.BLACK);

		plot.getGraphWidget().getDomainOriginLabelPaint().setColor(Color.BLACK);
		plot.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK);
		plot.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK);
		
		/*	plot.getGraphWidget().setMarginLeft(30);
		plot.getGraphWidget().setMarginBottom(10);*/
		
		//------------------------------------------------------
//		plot.getGraphWidget().setRangeOriginLinePaint(null);
//        plot.getGraphWidget().setDomainOriginLinePaint(null);
//        plot.getGraphWidget().setRangeLabelPaint(null);
//        plot.getGraphWidget().setDomainLabelPaint(null);
//        plot.setRangeLabel(null);
//        
//        plot.getLegendWidget().setVisible(false);
//        plot.getLayoutManager().remove(plot.getDomainLabelWidget());
//        
//        plot.getGraphWidget().setDomainOriginLinePaint(null);
//        
//        plot.getGraphWidget().setBackgroundPaint(null);
//        plot.setPlotMargins(0, 0, 0, 0);
//        plot.setPlotPadding(0, 0, 0, 0);
//        
//        plot.getGraphWidget().setMargins(0, 0, 0, 0);
//        plot.getGraphWidget().setPadding(0, 0, 0, 0);
//        plot.setGridPadding(0, 0, 0, 0);
//        plot.setDomainLabelWidget(null);
//        plot.setRangeLabelWidget(null);
//        plot.setLegendWidget(null);
//        plot.setTitleWidget(null);
	}
}
